package initialize

import (
	"context"
	"fmt"
	"go-learn/global"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

func Mongodb() *mongo.Database {
	mongoCfg := global.Config.MongoDB
	url := "mongodb://" + mongoCfg.Addr
	// 设置连接超时时间,time.Duration单位：ms
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(mongoCfg.TimeOut))
	defer cancel()
	option := options.Client().ApplyURI(url)
	// 设置最小、最大连接数
	option.SetMinPoolSize(uint64(mongoCfg.MinPoolSize)).SetMaxPoolSize(uint64(mongoCfg.MaxPoolSize))
	// 创建客户端
	client, err := mongo.Connect(ctx, option)
	if err != nil {
		panic(err)
	}
	// 查看连接是否正常
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		panic(err)
	}
	fmt.Println("connect mongo success")
	// 选择数据库
	db := client.Database(mongoCfg.DB)
	return db
}
